import threading
import time


def metronome(milliseconds, count, func, *args, **kwargs):
    interval = milliseconds / count / 1000.0  # 将间隔时间转换为秒
    stop_event = threading.Event()

    def worker():
        for _ in range(count):
            if stop_event.is_set():
                break
            start_time = time.time()
            func(*args, **kwargs)  # 调用传入的函数
            elapsed_time = time.time() - start_time
            time_to_wait = interval - elapsed_time
            if time_to_wait > 0:
                stop_event.wait(time_to_wait)  # 使用 Event 对象来等待

    thread = threading.Thread(target=worker)
    thread.start()
    return stop_event


# 示例函数
def your_function(name):
    print(f"Hello, {name}!")


# 使用示例
if __name__ == '__main__':
    stop_event = metronome(2000, 5, your_function)
